package com.rockblade.generator.utils.sql;

import com.github.pagehelper.PageHelper;
import com.rockblade.generator.core.page.PageDomain;
import com.rockblade.generator.core.page.TableSupport;
import com.rockblade.generator.exception.UtilException;
import com.rockblade.generator.utils.StringUtils;

/**
 * sql操作工具类
 *
 * @author DB
 */
public class SqlUtils {

    public SqlUtils() {
    }

    private static class SqlUtilInstance {
        private static final SqlUtils INSTANCE = new SqlUtils();
    }

    public static SqlUtils getInstance() {
        return SqlUtils.SqlUtilInstance.INSTANCE;
    }

    /**
     * 仅支持字母、数字、下划线、空格、逗号、小数点（支持多个字段排序）
     */
    public static String SQL_PATTERN = "[a-zA-Z0-9_\\ \\,\\.]+";

    /**
     * 检查字符，防止注入绕过
     */
    public String escapeOrderBySql(String value) {
        if (StringUtils.isNotEmpty(value) && !isValidOrderBySql(value)) {
            throw new UtilException("参数不符合规范，不能进行查询");
        }
        return value;
    }

    /**
     * 验证 order by 语法是否符合规范
     */
    public boolean isValidOrderBySql(String value) {
        return value.matches(SQL_PATTERN);
    }

    /**
     * 设置请求分页数据
     */
    public void startPage() {
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();
        if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize)) {
            String orderBy = escapeOrderBySql(pageDomain.getOrderBy());
            Boolean reasonable = pageDomain.getReasonable();
            PageHelper.startPage(pageNum, pageSize, orderBy).setReasonable(reasonable);
        }
    }

    /**
     * 设置请求排序数据
     */
    public void startOrderBy() {
        PageDomain pageDomain = TableSupport.buildPageRequest();
        if (StringUtils.isNotEmpty(pageDomain.getOrderBy())) {
            String orderBy = SqlUtils.getInstance().escapeOrderBySql(pageDomain.getOrderBy());
            PageHelper.orderBy(orderBy);
        }
    }
}
